package mc.support.web.action;

import mc.support.support.function.Closure;
import mc.support.web.WebConstants;
import mc.support.web.action.aware.CommonActionAware;
import mc.support.web.exception.BizErrorException;
import mc.support.web.exception.InvalidParamTypeException;
import mc.support.web.exception.ParamLostExcepion;
import mc.support.web.exception.ServiceException;
import mc.support.web.service.ServiceSupport;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: francis Yun    <br/>
 * Date: 2013-11-23  <br/>
 */
public abstract class ActionSupport extends ServiceSupport implements CommonActionAware {

    private static Logger log = LoggerFactory.getLogger( ActionSupport.class );

    private static final String DEFAULT_DATE_FORMAT = WebConstants.GLOBAL_DATE_FORMAT;
    private static SimpleDateFormat defaultDatFormat;
    private static FailureHandler defaultFailureHandler;
    private static ResultDecorator defaultResultDecorator;

    protected static SimpleDateFormat getDefaultDatFormat() {
        return defaultDatFormat;
    }

    protected static void setDefaultDatFormat(SimpleDateFormat defaultDatFormat) {
        ActionSupport.defaultDatFormat = defaultDatFormat;
    }

    public static void setDefaultFailureHandler(FailureHandler defaultFailureHandler) {
        ActionSupport.defaultFailureHandler = defaultFailureHandler;
    }

    public static void setDefaultResultDecorator(ResultDecorator defaultResultDecorator) {
        ActionSupport.defaultResultDecorator = defaultResultDecorator;
    }

    static {
        defaultDatFormat = new SimpleDateFormat( DEFAULT_DATE_FORMAT );
        defaultFailureHandler = new FailureHandlerAdaptor();
        defaultResultDecorator = new DefaultResultDecoratorImpl();
    }

    @Override
    public void init() {
        //do nothing here!
    }

    private Object getObject( Map<String, Object> params, String key) {
        if ( null == params || !StringUtils.isNotBlank( key ) ) {
            return null;
        }

        return params.get( key );
    }

    protected String getString( Map<String, Object> params, String key ) {
        return (String) getObject( params, key );
    }

    protected Boolean getBool( Map<String,Object> params, String key ) {
        String s = getString( params , key );
        return Boolean.valueOf( s );
    }

    protected Integer getInteger( Map<String, Object> params, String key) {
        String s = getString( params , key );

        if ( StringUtils.isNumeric( s ) ) {
            return Integer.valueOf( s );
        } else {
            return null;
        }
    }

    protected Long getLong( Map<String, Object> params, String key) {
        String s= getString( params, key );


        if ( StringUtils.isNumeric( s ) ) {
            return Long.valueOf( s );
        } else {
            return null;
        }

    }

    protected Long[] getLongArray( Map<String, Object> params, String key, String sep) {
        String s = getString( params, key );

        if ( StringUtils.isNotBlank( s ) ) {
            String[] ss = s.split( sep );

            int len = ss.length;
            Long[] l = new Long[ len ];
            for ( int i = 0; i < len; i++ ) {
                String numStr = ss[i].trim();
                if ( StringUtils.isNumeric( numStr ) ) {
                    l[i] = Long.valueOf( numStr );
                }
            }

            return l;
        } else {
            return null;
        }
    }

    protected Date getDate( Map<String, Object> params, String key) {
        String s = getString( params, key );

        Date d = null;
        if ( StringUtils.isNotBlank( s ) ) {
            try {
                d = defaultDatFormat.parse( s );
            } catch (ParseException e) {
                log.warn( "invalid date string : " + s  );
            }
        }
        return d;
    }

//    protected static interface Closure<T,E> {
//        public T go(E e);
//    }

    protected static interface FailureHandler {
        /*
        * return status code!
        * */
        public int handle(Exception e);
        public String makeMsg(Exception e);

    }

    protected static class FailureHandlerAdaptor implements FailureHandler {

        static final int NORMAL = 0;
        static final int LOST_PARAM = -1;
        static final int INVALID_PARAM_TYPE = -2;
        static final int SERVICE_ERROR = -3;
        static final int BIZ_ERROR=-4;
        static final int INNER_ERROR = -255;

        @Override
        public int handle(Exception e) {
            int status = NORMAL;

            if ( null != e ) {
                if ( e instanceof ParamLostExcepion ) {
                    status = LOST_PARAM;
                } else if ( e instanceof InvalidParamTypeException ) {
                    status = INVALID_PARAM_TYPE;
                } else if ( e instanceof ServiceException ) {
                    status = SERVICE_ERROR;
                } else if ( e instanceof BizErrorException ) {
                    status = BIZ_ERROR;
                } else {
                    status = INNER_ERROR;
                }
            }

            return status;
        }

        @Override
        public String makeMsg(Exception e) {
            if ( null != e ) {
                return e.getMessage();
            }
            return "";
        }

    }

    protected <R,P> Object process( P req, Closure<R,P> bizHandler) {
        return process( req, bizHandler, null, null );
    }

    protected <R,P> Object process( P req, Closure<R, P> bizHandler, FailureHandler failureHandler ) {
        return process( req, bizHandler, failureHandler, null );
    }

    protected <R,P> Object process( P req, Closure<R,P> bizHandler, ResultDecorator decorator) {
        return process( req, bizHandler, null, decorator );
    }

    protected <R,P> Object process( P req, Closure<R,P> bizHandler, FailureHandler failureHandler,
                                    ResultDecorator decorator ) {

        int status = 0;
        Object resp = null;
        String errMsg = null;
        try {
            resp = bizHandler.call(req);
        } catch (Exception e){
            if ( null == failureHandler ) {
                failureHandler = defaultFailureHandler;
            }
            status = failureHandler.handle( e );
            errMsg = failureHandler.makeMsg( e );
        }

        if ( null == decorator ) {
            decorator = defaultResultDecorator;
        }
        resp = decorator.decorate( resp, status, errMsg );

        return resp;
    }

}
